<?php
/**
 * 商品属性模型层
 * 
 * @copyright 	Copyright (c) 2011 thinkapk.com All rights reserved.
 * @package 	ThinkAPK_Model
 * @link 		http://www.thinkapk.com/
 * @author 		richie <richbossman@163.com>
 * @version 	$Id: GoodsAttrModel.class.php 7524 2011-05-30 05:18:37Z yemusheng $
 * 
 */
class GoodsAttrModel extends CommonModel {
	
	/**
	 * 属性价格计算
	 *
	 * @param string $spec
	 * @return float
	 */
	public function specPrice($spec=''){
		if(is_array($spec)){
			$spec = implode(',', $spec);
		}
		if(empty($spec)) return 0;
		$price = $this->where(array('goods_attr_id'=>array('IN', $spec)))->sum('attr_price');
		$price = floatval($price);
		return $price;
	}
	
	/**
	 *	取商品属性
	 *　@param int $goods_id		商品ID
	 */
	 public function getGoodsAttr($goods_id){
	 	if(!is_numeric($goods_id)) return array();
		
		$attrs=$this->field('goods_attr_id,g.attr_id,attr_name,attr_value,attr_price')->table(C('DB_PREFIX').'goods_attr g,'.C('DB_PREFIX').'attribute a')->where("goods_id={$goods_id} and g.attr_id=a.attr_id")->order('a.sort_order, g.attr_price, g.goods_attr_id')->select();
		if($attrs){
			/*将结果集格式化以下格式
			 $tmp[attr_id]=array(
			 	'attr_name'=>属性名,
				'attr_id'=>属性ID,
				'attr_values'=>array(
					[0]=>array(
						'goods_attr_id'=>属性值ID，
						'attr_value'=>属性值,
						'attr_price'=>属性值价格
					),
					[1]=>array(
						'goods_attr_id'=>属性值ID，
						'attr_value'=>属性值,
						'attr_price'=>属性值价格
					),
				)
				
			 )
			*/
			$tmp=array();
			foreach($attrs as $attr){
				if(isset($tmp[$attr['attr_id']])){
					$tmp[$attr['attr_id']]['attr_values'][]=array(
						'goods_attr_id'=>$attr['goods_attr_id'],
						'attr_value'=>$attr['attr_value'].($attr['attr_price']>0?' 加￥'.abs($attr['attr_price']).'元':($attr['attr_price']<0?' 减￥'.abs($attr['attr_price']).'元':'')),
						'attr_price'=>$attr['attr_price']
					);
				}else{
					$tmp[$attr['attr_id']]=array(
						'attr_name'=>$attr['attr_name'],
						'attr_id'=>$attr['attr_id']
					);
					$tmp[$attr['attr_id']]['attr_values'][]=array(
						'goods_attr_id'=>$attr['goods_attr_id'],
						'attr_value'=>$attr['attr_value'].($attr['attr_price']>0?' 加￥'.abs($attr['attr_price']).'元':($attr['attr_price']<0?' 减￥'.abs($attr['attr_price']).'元':'')),
						'attr_price'=>$attr['attr_price']
					);
				}
			}
			unset($attrs);
			return $tmp;
		}else return array();
	 }
	 
}
?>